﻿var g_bClosed = false;
var vdDiv = null;
var g_srcElement = null;
var g_timer = null;
var g_config = {
    config: [
        /*
        {
            site: "youku",
            id: "movie_player",
            data: "youku.com"
        },
        */
        {
            site: "tencent",
            id: "tenvideo_flash_player",
            data: "tencentvideo"
        },
        {
            site: "le",
            id: "www_player_1",
            data: "letvcdn.com"
        },
        {
            site: "mgtv",
            id: "hunantv-player-1",
            data: "MangoTV"
        },
        {
            site: "wasu",
            id: "wsplayer",
            data: "wasu.cn"
        },
        {
            site: "baofeng",
            id: "playg8rjst",
            data: "baofeng.com"
        },
        {
            site: "bilibili",
            id: "player_placeholder",
            data: "hdslb.com"
        },
        {
            site: "PPTV",
            id: "PPTV_PLAYER",
            data: "pplive.cn"
        },
        {
            site: "ku6",
            id: "ku6player",
            data: "ku6cdn.com"
        },
        {
            site: "weibo",
            id: "",
            data: "miaopai.com"
        },
        {
            site: "tangdou",
            id: "SwfObject",
            data: "bokecc.com"
        },
        {
            site: "cctv",
            id: "vplayer",
            data: "cntv.cn"
        },
        {
            site: "sohu",
            id: "player",
            data: "sohu.com"
        },
        {
            site: "youtube",
            id: "",
            data: "youtube.com"
        }
        /*
        {
            // 以iframe的形式内嵌优酷播放器 http://6pingm.com/dfwshlxjr/149677.html
            // 在iframe内部捕捉不到mousemove
            id: "youku-player",
            data: "youku.com",
            obj: "data"				
        },
        */
    ]
};

// function getVersion() {
//     var version = 'NaN';
//     var xhr = new XMLHttpRequest();
//     xhr.open('GET', chrome.extension.getURL('manifest.json'), false);
//     xhr.send(null);
//     var manifest = JSON.parse(xhr.responseText);
//     return manifest.version;
// }

// function httpRequest(url, callback){
//     var xhr = new XMLHttpRequest();
//     xhr.open("GET", url, true);
//     xhr.onreadystatechange = function() {
//         if (xhr.readyState == 4) {
//             callback(xhr.responseText);
//         }
//     }
//     xhr.send();
// }

function doVidp(url) {
    var vidpUrl = "vidp://download/" + url;
    var el = document.createElement("a");
    document.body.appendChild(el);
    el.href = vidpUrl;
    el.click();
    document.body.removeChild(el);
}

function vdFolatPannel() {
    document.body.onmousemove = function (e) {
        if (!e) {
            e = window.event;
        }
        else {
            e.srcElement = e.target;
        }
        g_srcElement = e.srcElement;

        if (g_bClosed == true)
            return;

        if ((e.srcElement.type == "application/x-shockwave-flash") || (e.srcElement.tagName.toLowerCase() == "video")) {
            // 判断一下是否是我们能够支持下载的（通过json数据）
            var bSupport = false;
            var i = 0;
            for (i = 0; i < g_config.config.length; ++i) {
                // 如果没有id的话就不用判断id是否相等了
                //console.log(e.srcElement.innerHTML);
                if ((!e.srcElement.id || e.srcElement.id.indexOf(g_config.config[i].id) >= 0) && e.srcElement.parentNode.innerHTML.indexOf(g_config.config[i].data) >= 0) {
                    bSupport = true;
                    break;
                }
            }
            if (!bSupport)
                return;

            var flash = e.srcElement;

            if (vdDiv == null) {
                vdDiv = document.createElement("div");
                vdDiv.id = "vidown_float_pannel_div";
                vdDiv.innerHTML = '<a id="vidown_float_pannel_download" title="用【维棠】下载视频">维棠下载</a><span style="color:#AAA;padding-left:6px;padding-right:6px">|</span><input type="button" value=" " id="vidown_float_pannel_close" title="关闭"></input>';

                flash.parentNode.appendChild(vdDiv);

                var btnDownload = document.getElementById("vidown_float_pannel_download");
                var btnClose = document.getElementById("vidown_float_pannel_close");

                btnDownload.onclick = function () {
                    var vidpUrl = "";
                    if (g_config.config[i].obj) {
                        vidpUrl = g_srcElement.getAttribute(g_config.config[i].obj);
                    };
                    if (vidpUrl == null || vidpUrl == "") {
                        vidpUrl = window.location.href;
                    }
                    // doVidp(vidpUrl);
                    chrome.runtime.sendMessage({ vidpFloatPannelMsg: vidpUrl });
                };

                btnClose.onclick = function () {
                    g_bClosed = true;
                    vdDiv.style.display = "none";
                };
            }
            if (g_bClosed == false) {
                vdDiv.style.display = "block";
            }

            // 修改 fix pos
            var flashPos = flash.getBoundingClientRect();
            var vdDivPos = vdDiv.getBoundingClientRect();
            vdDiv.style.left = flashPos.right - vdDivPos.width + "px";
            vdDiv.style.top = flashPos.top - vdDivPos.height + "px";
            if (parseInt(vdDiv.style.top) < 50) {
                // 针对youtube的情况
                vdDiv.style.top = flashPos.top + "px";
                vdDiv.style.left = flashPos.right + "px";
            }
        }
    };
}

window.addEventListener("load", function () {
    g_bClosed = false;

    // 应该在chrome启动的时候请求一次配置，而不是每次加载页面的时候都请求一次。相关数据保存到localstorage
    // var version = "1.4.4"; //getVersion();
    // console.log(version);
    // httpRequest('http://v.pi58.com/player/getplayerconfig.php?ver=' + version, function(result){
    //     g_config = JSON.parse(result);
    //     console.log(g_config.config);
    // });

    // 从localstorage读取配置信息
    //g_config.config = localStorage.getItem("config");
    //console.log(g_config.config);
});

// 会不会起很多定时器，影响效率？？？
setInterval(function () {
    if (g_bClosed == true || vdDiv == null || g_srcElement == null)
        return;

    if (g_srcElement.parentNode == vdDiv || g_srcElement == vdDiv || g_srcElement.type == "application/x-shockwave-flash") {
        vdDiv.style.display = "block";
    }
    else {
        vdDiv.style.display = "none";
    }
}, 1500);

function addExtId() {
    var b = document.body;
    var e = document.createElement("div");
    e.setAttribute("id", "Vidown_extension_alhnopeoagjmjfgcbnokcnagkecgdcdh");
    e.style.display = "none";
    b.appendChild(e);
}

vdFolatPannel();
addExtId();
